package com.bjtu.restaurantreviews.dao;
import com.bjtu.restaurantreviews.domain.Restaurant;
import com.bjtu.restaurantreviews.domain.Restaurant_;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * @Author: Chen
 * @Description: 拼接多条件sql语句
 * @Date: Created in 22:48 2018/5/9
 */

public class RestaurantSpec {

    public static Specification<Restaurant> getSpec(final String rtype , final String rcity, final String word, final String sort) {
        return new Specification<Restaurant>() {
            public Predicate toPredicate(Root<Restaurant> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 = null;
                //根据rtype精确筛选
                if(!(rtype.equalsIgnoreCase("全部"))) {
                    Predicate p2 = cb.equal(root.get(Restaurant_.rtype),rtype);
                    if(p1 != null) {
                        p1 = cb.and(p1,p2);
                    } else {
                        p1 = p2;
                    }
                }
                //根据word模糊查询
                if (!(word.isEmpty())) {
                    Predicate p31 = cb.like(root.get(Restaurant_.rcity),"%"+word+"%");
                    Predicate p32 = cb.like(root.get(Restaurant_.rtype),"%"+word+"%");
                    Predicate p33 = cb.like(root.get(Restaurant_.rname),"%"+word+"%");
                    Predicate p3 = cb.or(p31,p32,p33);
                    if (p1 != null) {
                        p1 = cb.and(p1,p3);
                    }else {
                        p1 = p3;
                    }
                }
                //根据rcity精确筛选
                if(!(rcity.equalsIgnoreCase("全部"))) {
                    Predicate p2 = cb.equal(root.get(Restaurant_.rcity), rcity);
                    if(p1 != null) {
                        p1 = cb.and(p1,p2);
                    } else {
                        p1 = p2;
                    }
                }
                if (p1!=null) {
                    query.where(p1);
                }
                //根据sort排序
                if (sort.equalsIgnoreCase("默认")){
                    query.orderBy(cb.desc(root.get(Restaurant_.rstar)));
                }else {
                    switch (sort){
                        case "口味":
                            query.orderBy(cb.desc(root.get(Restaurant_.rtaste)));
                            break;
                        case "环境":
                            query.orderBy(cb.desc(root.get(Restaurant_.renviro)));
                            break;
                        case "服务":
                            query.orderBy(cb.desc(root.get(Restaurant_.rservice)));
                            break;
                    }
                }
                return query.getRestriction();
            }
        };
    }

}

